/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package program.gui;

import java.awt.BorderLayout;
import java.awt.Image;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import program.bl.PDFViewerController;
import program.utilities.ImageRotator;
import program.utilities.ImageUtilities;
import program.utilities.PDFUtilities;

/**
 * Functionality: 1. proof if user wants to choose a bill which alread exists in
 * PDF 1.1.) if he wants to youse PDF, display the PDF, so he can check it 2.
 * create a new bill 2.1) display a dlg so that the user can scan or choose
 * images to create a new bill 2.1.1 : call a program to scan a picture 2.1.2 :
 * show jfilechooser to select an existing page 2.2 : user can change the order
 * of the pages, by showing an contextmenu when he clicks on a page 2.3 : user
 * can change the direction of the picture 2.4 : user can delte one page
 *
 * Responsible: Patrick, Bernhard
 */
public class CreateBillDlg extends javax.swing.JDialog {

    private ThumbnailPanel tp;
    private PDFViewerController pdfvc = PDFViewerController.getInstance();
    private File finishedPDF;
    private boolean ok;
    private int i = 450;

    /**
     * Creates new form CreateBillDlg
     */
    public CreateBillDlg(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        tp = new ThumbnailPanel(ThumbnailPanel.ORDER_HORIZONTAL, center);
        try {
            south.add(tp, BorderLayout.CENTER);
            tp.draw();
        } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, ex);

        }
        this.setIcons();
        pack();
        setLocationRelativeTo(parent);
        this.setSize(450, 450);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        south = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        east = new javax.swing.JPanel();
        btright = new javax.swing.JButton();
        btleft = new javax.swing.JButton();
        btdelete = new javax.swing.JButton();
        btNewPage = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        center = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        south.setLayout(new java.awt.BorderLayout());

        jButton1.setText("Fertig");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onFinish(evt);
            }
        });
        south.add(jButton1, java.awt.BorderLayout.LINE_END);

        getContentPane().add(south, java.awt.BorderLayout.PAGE_END);

        east.setLayout(new java.awt.GridBagLayout());

        btright.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rotateRight(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        east.add(btright, gridBagConstraints);

        btleft.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onRotateLeft(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        east.add(btleft, gridBagConstraints);

        btdelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onDeletePage(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        east.add(btdelete, gridBagConstraints);

        btNewPage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onAddNewPage(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        east.add(btNewPage, gridBagConstraints);

        getContentPane().add(east, java.awt.BorderLayout.LINE_END);

        javax.swing.GroupLayout centerLayout = new javax.swing.GroupLayout(center);
        center.setLayout(centerLayout);
        centerLayout.setHorizontalGroup(
            centerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 437, Short.MAX_VALUE)
        );
        centerLayout.setVerticalGroup(
            centerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 362, Short.MAX_VALUE)
        );

        jScrollPane1.setViewportView(center);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Rotates image thumbnail to the right
     *
     * @param evt ButtonEvent
     */
    private void rotateRight(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rotateRight
        if (pdfvc.getNumberOfPages() > 0) {
            int pageNumber = tp.getCurrentPage();
            Image img = pdfvc.getPage(pageNumber - 1);
            Image img2 = ImageRotator.rotateImage(ImageUtilities.convertImageToBufferdImage(img), 90);
            this.updateMainPanel(img2);
            pdfvc.updatePage(pageNumber, img2);
        }
    }//GEN-LAST:event_rotateRight

    /**
     * Rotates image thumbnail to the left
     *
     * @param evt ButtonEvent
     */
    private void onRotateLeft(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onRotateLeft
        if (pdfvc.getNumberOfPages() > 0) {
            int pageNumber = tp.getCurrentPage();
            Image img = pdfvc.getPage(pageNumber - 1);
            Image img2 = ImageRotator.rotateImage(ImageUtilities.convertImageToBufferdImage(img), 270);
            this.updateMainPanel(img2);
            pdfvc.updatePage(pageNumber, img2);
        }
    }//GEN-LAST:event_onRotateLeft

    /**
     * Deletes page from the PDFViewerController
     *
     * @param evt ButtonEvent
     */
    private void onDeletePage(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onDeletePage
        if (pdfvc.getNumberOfPages() > 0) {
            int pageNumber = tp.getCurrentPage();
            if (pageNumber > 0 && center.getComponentCount() >= 1) {
                System.out.println("p:" + pageNumber);
                pdfvc.deletePage(pageNumber);


                this.updateMainPanel(null);

                tp.draw();
                tp.updateUI();
            }
        }
    }//GEN-LAST:event_onDeletePage

    /**
     * Call TwainGui to scan new page
     * Add the page to PDFViewerController
     *
     * @param evt ButtonEvent
     */
    private void onAddNewPage(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onAddNewPage
        //let the user choose if he wants to scan or choose a picture
        Object[] options = {"Scannen", "Vorhanedes Bild auswählen"};
        String text = "Möchten Sie eine neue Seite scannen oder eine bereits bestehende auswählen?";
        String title = "Neue Seite hinzufügen";

        int selected = JOptionPane.showOptionDialog(null, text, title, 0, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
        if (selected == 0) {
            try {
                Runtime.getRuntime().exec("cmd /c start programs\\TwainGui.exe");
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, ex);
            }

            Object[] scanOptions = {"Scannen beendet", "Abbrechen"};
            String scanText = "Haben Sie Ihren Scannvorgang bereits beendet?";
            String scanTile = "Neue Seite scannen";
            int scanSelected = JOptionPane.showOptionDialog(null, scanText, scanTile, 0, JOptionPane.QUESTION_MESSAGE, null, scanOptions, scanOptions[0]);
            if (scanSelected == 0) {
                try {
                    Runtime.getRuntime().exec("cmd /c taskkill /im TwainGui.exe");

                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(null, ex);
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    JOptionPane.showMessageDialog(null, ex);
                }
                File f = new File(System.getProperty("java.io.tmpdir") + File.separator + "pictures");
                if (f.exists()) {
                    File[] fileArray = f.listFiles();
                    if (fileArray.length > 0) {
                        for (int i = 0; i < fileArray.length; i++) {
                            File file = fileArray[i];
                            if (file != null || !file.getName().endsWith("jpg") || !file.getName().endsWith("jepg") || !file.getName().endsWith("png")) {
                                try {

                                    Image img = ImageIO.read(file);
                                    pdfvc.addPage(img);
                                    tp.draw();
                                    tp.updateUI();


                                } catch (IOException ex) {
                                    Logger.getLogger(CreateBillDlg.class.getName()).log(Level.SEVERE, null, ex);
                                }
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "Es wurde nichts eingescannt!", "Scann Error", JOptionPane.ERROR_MESSAGE);
                    }
                    try {
                        Runtime.getRuntime().exec("cmd /c rmdir /s /q " + System.getProperty("java.io.tmpdir") + File.separator + "pictures");
                    } catch (IOException ex) {
                        Logger.getLogger(CreateBillDlg.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Es wurde nichts eingescannt!", "Scann Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else if (selected == 1) {
            //user wants to choose his own picture
            JFileChooser jfc = new JFileChooser();
            jfc.setFileFilter(new FileNameExtensionFilter("Bilder", "jpg", "jpeg", "png"));
            jfc.showOpenDialog(this);
            File f = jfc.getSelectedFile();
            if (f != null || !f.getName().endsWith("jpg") || !f.getName().endsWith("jepg") || !f.getName().endsWith("png")) {
                try {
                    Image img = ImageIO.read(f);
                    pdfvc.addPage(img);
                    tp.draw();
                    tp.updateUI();
                } catch (IOException ex) {
                               JOptionPane.showMessageDialog(null, ex);

                }
            } else {
                JOptionPane.showMessageDialog(this, "Sie haben kein gültiges Bild ausgewählt!", "Error!", JOptionPane.ERROR_MESSAGE);
            }
        }
        i++;
        this.setSize(450, i);
    }//GEN-LAST:event_onAddNewPage

    /**
     * Calls createPDF to write pages from PDFViewerController to pdf-file
     * Set dialog-control-variable true
     *
     * @param evt ButtonEvent
     */
    private void onFinish(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onFinish
        try {
            finishedPDF = PDFUtilities.createPDF(pdfvc.getAllImages());
            ok = true;
            this.setVisible(false);
        } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, ex);

        }
    }//GEN-LAST:event_onFinish

    /**
     * Sets icons for the buttons
     */
    private void setIcons() {
        try {
            btright.setIcon(new ImageIcon(ImageIO.read(new File("src\\program\\icons\\right.png"))));
            btleft.setIcon(new ImageIcon(ImageIO.read(new File("src\\program\\icons\\left.png"))));
            btdelete.setIcon(new ImageIcon(ImageIO.read(new File("src\\program\\icons\\delete.png"))));
            btNewPage.setIcon(new ImageIcon(ImageIO.read(new File("src\\program\\icons\\new.png"))));
        } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, ex);

        }
    }

     /**
      * Updates the panel where thumbnails are viewed.
      * 
      * @param img Image which is viewed
      */
    private void updateMainPanel(Image img) {
        center.removeAll();
        if (img != null) {
            center.add(new JLabel(new ImageIcon(img)));
        }
        center.updateUI();
    }

    /**
     * Returns finished pdf
     * 
     * @return finished pdf
     */
    public File getFinishedPDF() {
        return finishedPDF;
    }

    /**
     * Returns dialog-control-variable for the parent component
     *
     * @return dialog-control-variable
     */
    public boolean isOk() {
        return ok;
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btNewPage;
    private javax.swing.JButton btdelete;
    private javax.swing.JButton btleft;
    private javax.swing.JButton btright;
    private javax.swing.JPanel center;
    private javax.swing.JPanel east;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel south;
    // End of variables declaration//GEN-END:variables
}
